package com.linkrenhe.frame.http;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import com.sczmgk.hotline_pzh.utils.BitmapUtils;
import com.sczmgk.hotline_pzh.utils.MyLog;
import com.sczmgk.hotline_pzh.utils.Tools;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.os.Environment;

public class FileUtil {
	private static final Object mLockObject = new Object();
	private static final String TAG = FileUtil.class.getSimpleName();
	public static String ROOT_PATH = null;
	public static boolean avaiableSDCard() {
		String status = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(status))
			return true;
		else
			return false;
	}
	public static boolean saveFile2SDCard(String fileName, InputStream inStream)
			throws IOException {
		boolean flag = false;
		FileOutputStream fs = null;
		
		try {
			if (!Tools.isEmpty(fileName) && inStream != null) {
				
				File file = newFileWithPath(fileName.toString());
				if (file.exists()) {
					file.delete();
					MyLog.w(TAG,"httpFrame  threadName:"+Thread.currentThread().getName()+"........ "+ fileName.toString());
				}
				
				fs = new FileOutputStream(file);
				byte[] buffer = new byte[1024];
				int len = -1;

				while ((len = inStream.read(buffer)) != -1) {
					fs.write(buffer, 0, len);
				}

				flag = true;

				MyLog.i(TAG, "httpFrame  threadName:"+Thread.currentThread().getName()+" ............: "+fileName.toString());
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fs != null)
				fs.close();
		}

		return flag;
	}
	public static boolean saveFile2SDCard(String fileName, byte[] dataBytes)
			throws IOException {
		boolean flag = false;
		FileOutputStream fs = null;
		try {
			if (!Tools.isEmpty(fileName)) {
				File file = newFileWithPath(fileName.toString());
				if (file.exists()) {
					file.delete();
					MyLog.w(TAG,"httpFrame  threadName:"+Thread.currentThread().getName()+" ==: "+ fileName.toString());
				}
				fs = new FileOutputStream(file);
				fs.write(dataBytes, 0, dataBytes.length);
				fs.flush();
				flag = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fs != null)
				fs.close();
		}

		return flag;
	}

	public static byte[] readStream(InputStream inStream) throws IOException {
		ByteArrayOutputStream outstream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = -1;
		while ((len = inStream.read(buffer)) != -1) {
			outstream.write(buffer, 0, len);
		}

		return outstream.toByteArray();
	}
	public static String readStreamToString(InputStream inStream) throws IOException {
		InputStreamReader isr = new InputStreamReader(inStream);
		BufferedReader br = new BufferedReader(isr);
		
		StringBuffer sb = new StringBuffer();
		String s = null;
		while((s = br.readLine()) != null){
			sb.append(s);
			sb.append("\r\n");
		}
		br.close();
		return sb.toString();
	}
	private static File newFileWithPath(String filePath){
		if(Tools.isEmpty(filePath)){
			return null;
		}
		
		int index = filePath.lastIndexOf(File.separator);
		
		String path = "";
		if(index != -1){
			path = filePath.substring(0, index);
			if(!Tools.isEmpty(path)){
				File file = new File(path.toString());
				if (!file.exists() && !file.isDirectory()) {
					boolean flag = file.mkdirs();
					if (flag) {
						MyLog.i(TAG,"httpFrame  threadName:"+Thread.currentThread().getName()+" ..."+ file.getPath());
					} else {
						MyLog.e(TAG,"httpFrame  threadName:"+Thread.currentThread().getName()+" ..."+ file.getPath());
					}
				}
			}
		}
		return new File(filePath);
	}
    public static boolean delete(String fileName){   
        File file = new File(fileName);   
        if(!file.exists()){   
            return false;   
        }else{   
            if(file.isFile()){   
                   
                return deleteFile(fileName);   
            }else{   
                return deleteDirectory(fileName);   
            }   
        }   
    }   
    public static boolean deleteFile(String fileName){   
    	return deleteFile(fileName, false);
    }   
    public static boolean deleteFile(String fileName,boolean isTemp){   
    	if(fileName!=null){
    		String logFile  = "";
    		if(isTemp){
    			logFile= "--";
    		}else{
    			logFile= "--";
    		}
            File file = new File(fileName);   
            if(file.isFile() && file.exists()){   
                file.delete();   
                return true;   
            }else{   
                return false;   
            }
    	}
    	return false;
    	
    }   
    public static boolean deleteDirectory(String dir){   
        if(!dir.endsWith(File.separator)){   
            dir = dir+File.separator;   
        }   
        File dirFile = new File(dir);   
        if(!dirFile.exists() || !dirFile.isDirectory()){   
            return false;   
        }   
        boolean flag = true;   
        File[] files = dirFile.listFiles();   
        for(File file : files){   
            if(file.isFile()){   
                flag = deleteFile(file.getAbsolutePath());   
                if(!flag){   
                    break;   
                }   
            }   
            else{   
                flag = deleteDirectory(file.getAbsolutePath());   
                if(!flag){   
                    break;   
                }   
            }   
        }   
           
        if(!flag){   
            return false;   
        }   
        
        if(dirFile.delete()){   
            return true;   
        }else{   
            return false;   
        }   
    }
    public static long getSDFreeSize(){
    	
    	return getSDFreeSize(Environment.getExternalStorageDirectory().toString());
    }
    public static long getSDFreeSize(String filePath){
    	try{
    		File file = new File(filePath);
        	if(!file.exists()){
        		file.mkdirs();
        	}
        	
    		android.os.StatFs statfs = new android.os.StatFs(filePath);

    		long nBlocSize = statfs.getBlockSize(); 

    		long nAvailaBlock = statfs.getAvailableBlocks(); 

    		long nSDFreeSize = nAvailaBlock * nBlocSize; 
    												
    		return nSDFreeSize;
    	}catch(Exception ex){
    		ex.printStackTrace();
    		MyLog.i(TAG, "httpFrame threadName:"+Thread.currentThread().getName()+" getSDFreeSize  folderPath:"+filePath);
    	}
    	
		return -1;
	}
    public static String splitJointPath(String prePath,String fileNamePath){
    	if(prePath == null || fileNamePath == null){
    		return "";
    	}
    	String path = "";
    	if(prePath.endsWith("/")){
    		if(fileNamePath.startsWith("/")){
    			path = prePath+fileNamePath.substring(1);
    		}else{
    			path = prePath+fileNamePath;
    		}
    	}else{
    		if(fileNamePath.startsWith("/")){
    			path = prePath+fileNamePath;
    		}else{
    			path = prePath+"/"+fileNamePath;
    		}
    	}
    	return path;
    }
    
    public static long getBitmapLength(Bitmap bitmap){
    	return bitmap.getRowBytes()*bitmap.getHeight();
    }
	public static String saveBitmap(String fileRootPath,Bitmap bm,CompressFormat format,String extension){
		
		if(createFolder(fileRootPath)){
			long bitmapSize=getBitmapLength(bm);
			
			FileOutputStream fos = null;
			if(getSDFreeSize(fileRootPath)<=bitmapSize){
				MyLog.e(TAG, "httpFrame  threadName:"+Thread.currentThread().getName()+" saveBitmap  :"+fileRootPath);
				return null;
			}
			
			try{
				String filePath = fileRootPath +File.separator+getTimeMillisFileName();
				if(extension!=null&&extension.length()>0){
					filePath = filePath+"."+extension;
				}
				
				File file=new File(filePath);
				file.createNewFile();
				fos=new FileOutputStream(file);
				bm.compress(format, 100, fos);
				return filePath;
				  
			}catch (Exception e) {
				e.printStackTrace();
			}finally{
				try {
					if(fos != null){
							fos.flush();
							fos.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}else{
		}
		
		return null;
	}
	
	
	
	
	public static String saveFile(String fileRootPath,String extension,byte[] bytes){
		
		
		return saveFile(fileRootPath, extension, bytes, false);
	}
	
	public static String saveFile(String fileRootPath,String extension,byte[] bytes,boolean isTemp){
		String logFile  = "";
		if(isTemp){
			logFile= "---";
		}else{
			logFile= "---";
		}
		
		
		if(createFolder(fileRootPath)){
			long bitmapSize=bytes.length;
			
			FileOutputStream fos = null;
			if(getSDFreeSize(fileRootPath)<=bitmapSize){
				return null;
			}
			
			try{
				String filePath = fileRootPath +File.separator+getTimeMillisFileName()+"."+extension;
				File file=new File(filePath);
				file.createNewFile();
				
				fos=new FileOutputStream(file);
				fos.write(bytes,0,bytes.length);
				return filePath;
				  
			}catch (Exception e) {
				e.printStackTrace();
			}finally{
				try {
					if(fos != null){
						fos.flush();
						fos.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}else{
		}
		
		return null;
	}
	
	public static boolean createFolder(String folderPath){
		File file=new File(folderPath);
		if(!file.exists()){
			return file.mkdirs();
		}
		return true;
	}
	
	public static String getFileName(String filePath){
		if(filePath.length()>0 && filePath!=null){  
			int i = filePath.lastIndexOf("/");
			return filePath.substring(i+1, filePath.length());
		} 
		return null;
	}
	
	public static long getFileLength(String filePath){
		if(filePath!=null){
			File file = new File(filePath);
			if(file.isFile()){
				return file.length();
			}
		}
		return -1;
	}
	
	public static String getExtensionName(String filePath){
		if(filePath==null){
			return null;
		}
		
		int indexSeparator = filePath.lastIndexOf(File.separator);
		if(filePath.indexOf(".", indexSeparator)<0){
			return null;
		}
		
		if(filePath!=null&&filePath.length()>0 ){  
			int i = filePath.lastIndexOf(".");
			if(i>=0){
				return filePath.substring(i+1, filePath.length());
			}else{
				return "";
			}
		} 
		return null;
	}
	
	public static String getFolderPath(String filePath){
		if(filePath.length()>0 && filePath!=null){  
			int i = filePath.lastIndexOf("/");
			return filePath.substring(0, i);
		} 
		return null;
	}
	
	public static String compressImagePath(Bitmap image,String savePath,String extension) throws IOException {   
		byte[] byteArrary = compressImageByte(image,extension);
		String filePath = FileUtil.saveFile(savePath, extension, byteArrary,true);
		return filePath;
	}
	
	public static byte[] compressImageByte(Bitmap image,String extension) throws IOException {   
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		CompressFormat format = null;
		if(BitmapUtils.EXTENSION_IMG_JPEG.equals(extension)){
			format = CompressFormat.JPEG;
		}else{
			format = CompressFormat.PNG;
		}
		image.compress(format, 100, baos);
		int options = 100;   
		while ( baos.toByteArray().length / 1024>150) {      
			baos.reset();
			image.compress(format, options, baos);
			if(options<=40){
				break;
			}
			options -= 10;  
		}
		byte[] byteArrary =  baos.toByteArray();
		baos.flush();
		baos.close();
		System.gc();
		return byteArrary;
	}
	
	public static boolean copyFile(File srcPath,File destPath){
		InputStream in = null;
		OutputStream out = null;
		try {
			in = new FileInputStream(srcPath);
			out = new FileOutputStream(destPath);

			byte[] buffer = new byte[1024];

			int length;
			
			while ((length = in.read(buffer)) > 0) {
				out.write(buffer, 0, length);
			}
			return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			try {
				if(in!=null){
					in.close();
				}
				if(out!=null){
					out.flush();
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
		return false;
	}
	
	public static String getTimeMillisFileName(){
		synchronized (mLockObject) {
			long curTime = System.currentTimeMillis();
			while(true){
				long time = System.currentTimeMillis();
				if(time-curTime>0){
					return ""+time;
				}
			} 
		}
	}
	
	
	public static void initTempRootPath(Context context){
		ROOT_PATH = getAppStorageDir(context);
	}
	private static String getAppStorageDir(Context context) {
		File f = context.getExternalFilesDir(null);
		if (f == null) {
			String storageDirectory = Environment.getExternalStorageDirectory()
					.toString();
			File fDir = new File(storageDirectory);
			if (!fDir.canWrite()) {
				storageDirectory = getSDCardDir();
				if (storageDirectory != null) {
					storageDirectory = storageDirectory + File.separator + "pingan_upload";
					MyLog.i(TAG, "  storageDirectory:"+storageDirectory);
					return storageDirectory;
				}
			} else {
				storageDirectory = storageDirectory + File.separator + "pingan_upload";
				MyLog.i(TAG, "storageDirectory:"+storageDirectory);
				return storageDirectory;
			}
		} else {
			String storageDirectory = f.getAbsolutePath() + File.separator + "pingan_upload";
			MyLog.i(TAG, "storageDirectory:"+storageDirectory);
			return storageDirectory;
		}
		MyLog.w(TAG, "---------------");
		return null;
	}
	
	private static String getSDCardDir() {
		String pathDir = null;
		File sdfile = Environment.getExternalStorageDirectory();
		File parentFile = sdfile.getParentFile();
		File[] listFiles = parentFile.listFiles();

		long freeSizeMax = 0L;
		for (int i = 0; i < listFiles.length; i++) {
			if (listFiles[i].canWrite()) {
				String tempPathDir = listFiles[i].getAbsolutePath();
				long tempSize = getSDFreeSize(tempPathDir);
				if (tempSize > freeSizeMax) {
					freeSizeMax = tempSize;
					pathDir = tempPathDir;
				}
			}
		}
		return pathDir;
	}
	
	public static boolean isFile(String filePath){
		if(filePath!=null && !filePath.trim().equals("")){
			return new File(filePath).isFile();
		}
		return false;
		
	}

	
}
